/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#ifndef IO_CC
#define IO_CC
#include "io.h"
#include "simple.h"
#include "error.h"
#include <string.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>

void elog_io_helper()
{
	printf
	    ("Copyright 2003 Chris Hilton, licensed Open Source under GPL.\n");
	printf
	    ("Free for distribution and resale, please send code changes to madcompnerd@hotmail.com\n");
	printf("Options:\n");
	printf
	    ("d      Decrypts file, also send filename:  encrypt -d filenameX\n");
	printf
	    ("e      Encrypts file, also send filename: encrypt -d filenameX\n");
	printf
	    ("t      Traverses directory and subdirectories, searching each file for $term: encrypt -r dir $term\n");
	printf
	    ("s      Searches $file for $term: encrypt -s $file $term\n");
	printf("h      Prints this.\n");
	printf
	    ("Putting a number after the whole command will change the max size allowed for encryption and decryption.\n");
	printf
	    ("The default is 1024k; enter number in kilobytes.  Max filesize is 4GB.\n");

}





unsigned char *elog_io_readRestofFile(struct elog_io_file *in,
				      unsigned int *len)
{
	//should be this
	long x = ftell(in->file);
	fseek(in->file, 0, SEEK_END);
	long y = ftell(in->file);
	fseek(in->file, x, SEEK_SET);
	*len = (y - x);
	unsigned char *z = malloc((sizeof *z) * (*len + 1));
	fread(z, 1, y - x, in->file);
	return z;
}
char *elog_io_reader(const char *fileName, int *length)
{
	FILE *in = fopen(fileName, "rb");
	fseek(in, 0, SEEK_END);
	int len = ftell(in);
	fseek(in, 0, SEEK_SET);

	char *doc = malloc((sizeof *doc) * (len + 1));
	doc[len] = '\0';
	fread(doc, len, 1, in);

	fclose(in);
	return doc;
}

bool elog_io_writer(char *fileName, char *text, long *len)
{
	len = malloc(sizeof *len);
	FILE *out = fopen(fileName, "w");
	fwrite(text, *len, sizeof(char), out);
	fclose(out);
	return 1;
}

void elog_io_readLine(char *doc, struct elog_io_file *in, int chunk)
{
	fread(doc, sizeof *doc, chunk, in->file);
}
struct elog_io_file *elog_io_initialize(const char *fileName, int mode)
{
	char *x;
	x = malloc((sizeof *x) * 4);
	x[1] = 'b';
	x[2] = '\0';

	if (mode == ELOG_IO_WRITE)
		x[0] = 'w';
	else if (mode == ELOG_IO_RW) {
		x[3] = '\0';
		x[2] = '+';
	} else if (mode == ELOG_IO_READ)
		x[0] = 'r';
	else
		return NULL;


	const char *file = fileName;
	char **path = NULL;;
	if (mode == ELOG_IO_WRITE || mode == ELOG_IO_RW) {
		if (fileName[0] == '/') {
			path = elog_sp_breakToArr(&fileName[1], '/');
			chdir("/");
		} else
			path = elog_sp_breakToArr(fileName, '/');


		int i;

		for (i = 0; path[i + 1] != NULL; ++i) {

			if (chdir(path[i]) != 0) {
#ifndef WIN32
				mkdir(path[i],
				      S_IRUSR | S_IWUSR | S_IXUSR);
#else
				mkdir(path[i]);
#endif
				if (chdir(path[i]) != 0) {
					elog_err_print_console
					    ("Oops: Invalid Directory Name | Bad Permissions: io::initialize:  ");
					elog_err_print_console(path[i]);
					elog_err_print_console("\n");
					return NULL;
				}
			}
		}
		file = path[i];
	}
	struct elog_io_file *in = malloc((sizeof *in));
	in->file = fopen(file, x);
	if (in->file == NULL) {
		free(in);
		in = NULL;
	}
	free(x);
	int c;
	if (path != NULL) {
		for (c = 0; path[c] != NULL; ++c)
			free(path[c]);
		free(path);
	}
	return in;
}
int elog_io_mkdir(const char *dir)
{
#ifndef WIN32
	return (mkdir(dir, S_IRUSR | S_IWUSR | S_IXUSR) != 0);
#else
	return (mkdir(dir) != 0);
#endif
}

void elog_io_setHandle(struct elog_io_file *f, int loc)
{
	fseek(f->file, loc, SEEK_SET);
}

void elog_io_close(struct elog_io_file *f)
{
	fclose(f->file);
	free(f);
}
void elog_io_writeLine(struct elog_io_file *f, const void *data,
		       unsigned int len)
{
	if (data == NULL)
		fputs("", f->file);
	else if (len == 0)
		fwrite(data, strlen(data), sizeof *data, f->file);
	else
		fwrite(data, sizeof(unsigned char), len, f->file);
}
char *elog_io_read_realLine(struct elog_io_file *f)
{
	char *ret = malloc((sizeof *ret) * 100);
	int size = 100;


	char ch;
	int i = 0;
	while (1) {
		ch = fgetc(f->file);
		if (ch == '\n' || feof(f->file))
			break;
		if (i >= size - 1) {
			char *t_1;
			t_1 = malloc((sizeof *t_1) * (size * 2));
			t_1 = '\0';
			ret[size] = '\0';
			strcpy(t_1, ret);	//copy contents
			free(ret);
			ret = t_1;
			size = size * 2;
		}		//size updated if necessary
		ret[i] = ch;


		++i;
	}
	if (i <= 1) {
		free(ret);
		return NULL;
	}
	ret[i] = '\0';
	return ret;
}
char **elog_io_dirContents(const char *dir)
{
	char **ans = malloc((sizeof *ans) * 100);
	int l;
	for (l = 0; l < 100; ++l)
		ans[l] = NULL;
	DIR *d = opendir(dir);
	if (d == NULL)
		return ans;
	struct dirent *ent;
	int c = 0;
	while ((ent = readdir(d)) != NULL) {
		if ((c + 1) % 100 == 0)	//every 100th, right before it
		{
			char **t = malloc((sizeof *t) * (c + 100));

			for (l = 0; l < c; ++l)
				t[l] = ans[l];
			for (; l < c + 100; ++l)
				t[l] = NULL;
			free(ans);
			ans = t;
		}
		if (ent->d_name[0] != '.') {
			ans[c] =
			    malloc((sizeof *(ans[c])) *
				   (strlen(ent->d_name) + 1));
			ans[c][0] = '\0';
			strcat(ans[c], ent->d_name);
			++c;
		}


	}
	closedir(d);
	return ans;
}

struct elog_io_dir *elog_io_recurseDir(const char *dir, const char *path)
{

	DIR *cwd = opendir(".");
#ifndef WIN32
	int icwd = dirfd(cwd);
#else

#endif

	chdir(dir);

	struct elog_io_dir *head = malloc((sizeof *head) * 1);
	head->dir = elog_io_dirContents(".");	//we're already in this directory!
	head->subDir = malloc((sizeof *(head->subDir)) * 50);
	int c;
	int size = 50;
	for (c = 0; c < 50; ++c)
		head->subDir[c] = NULL;
	int j = 0;
	for (c = 0; head->dir[c] != NULL; ++c) {
		int ch1 = chdir(head->dir[c]);

		if (0 == ch1) {
			chdir("..");
			char *subpath;
			elog_sp_cat(&subpath, path, "/", head->dir[c], "/",
				    NULL);

			head->subDir[j] =
			    elog_io_recurseDir(head->dir[c], subpath);
			free(subpath);
			char *tmp;
			elog_sp_cat(&tmp, "///", head->dir[c], NULL);
			free(head->dir[c]);
			head->dir[c] = tmp;

			++j;
			if (j >= size) {
				struct elog_io_dir **tmp =
				    malloc((sizeof *tmp) * (size * 2));
				int l;
				for (l = 0; l < size; ++l)
					tmp[l] = head->subDir[l];
				free(head->subDir);
				head->subDir = tmp;
			}
		}
	}

#ifndef WIN32
	fchdir(icwd);
#else

#endif
	closedir(cwd);

	elog_sp_cat(&(head->path), path, NULL);
	return head;
}
void elog_io_dir_free(struct elog_io_dir *dir)
{
	int c;
	for (c = 0; dir->dir[c] != NULL; ++c)
		free(dir->dir[c]);
	for (c = 0; dir->subDir[c] != NULL; ++c)
		elog_io_dir_free(dir->subDir[c]);
	free(dir->dir);
	free(dir->subDir);
	free(dir->path);
	free(dir);
}

char *elog_io_date()
{
	time_t t;
	t = time(&t);
	return ctime(&t);
}

int elog_io_stat(const char *file)
{
	struct stat buf;
	if (stat(file, &buf))
		return ELOG_IO_STAT_ERR;	//error

	if (S_ISDIR(buf.st_mode))
		return ELOG_IO_STAT_DIR;
	if (S_ISREG(buf.st_mode))
		return ELOG_IO_STAT_FILE;
	if (S_ISFIFO(buf.st_mode))
		return ELOG_IO_STAT_FIFO;
#ifndef WIN32
	if (S_ISSOCK(buf.st_mode))
		return ELOG_IO_STAT_SCK;
	if (S_ISLNK(buf.st_mode))	//these are only available on real OS's
		return ELOG_IO_STAT_LNK;
#endif
	return ELOG_IO_STAT_OTHER;
}


#endif
